import { createStore } from "vuex"

export default createStore({
  // 数据源 Store.state.xxx
  state: {
    user: {}, // 用户信息
    menu: [] // 菜单权限
  },
  // 派生数据 Store.getters.xxx
  getters: {
    // 获取当前-用户对象
    GET_USER: state => {
      const data: string | null = sessionStorage.getItem('USER')
      if (data) {
        state.user = JSON.parse(data)
      } else {
        state.user = {}
      }
      return state.user
    },
    // 获取当前-菜单
    GET_MENU: state => {
      const data: string | null = sessionStorage.getItem('MENU')
      if (data) {
        state.menu = JSON.parse(data)
      } else {
        state.menu = []
      }
      return state.menu
    }
  },
  // 更改数据-同步 Store.commit('xxx', data)
  mutations: {
    // 保存当前-用户对象
    SET_USER: (state: any, data: object) => {
      state.user = data
      sessionStorageSet('USER', data)
    },
    // 保存当前-用户菜单
    SET_MENU: (state: any, data: Array<object>) => {
      state.menu = data
      sessionStorageSet('MENU', data)
    }
  }
})

// 本地存储-修改值
function sessionStorageSet (key: string, data: any) {
  if (data) {
    sessionStorage.setItem(key, JSON.stringify(data))
  } else {
    sessionStorage.removeItem(key)
  }
}
